package com.edgar.plugin.hooks;

import android.content.Context;
import android.util.Log;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Edgar on 2018/2/8.
 */
public class Hook implements InvocationHandler{

    private static final String TAG = "Hook";
    private Context mContext;
    private Object mOldObject;
    private Map<String,HookMethodHandle> mHookMethodHandles = new HashMap<>();

    public Hook(Context context){
        mContext = context;
    }

    public Context getContext() {
        return mContext;
    }

    public void setOldObject(Object oldObject){
        mOldObject = oldObject;
    }

    public final void install(){
        onInstall(mContext);
        onInitHookMethodHandle(mHookMethodHandles);
    }

    protected void onInstall(Context context){}
    protected void onInitHookMethodHandle(Map<String,HookMethodHandle> hookMethodHandles){}

    @Override
    public final Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Log.d(TAG,"Invoke hook method:"+method.getName());
        HookMethodHandle hookMethodHandle = mHookMethodHandles.get(method.getName());
        if (hookMethodHandle != null){
            return hookMethodHandle.onInvoke(mOldObject,method,args);
        }
        return method.invoke(mOldObject,args);
    }
}